package com.cn.transfer.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cn.transfer.common.constant.KeyConstant;
import com.cn.transfer.common.entity.MainFormData;
import com.cn.transfer.common.entity.jiandaoyun.JdyPurchaseOrder;
import com.cn.transfer.common.entity.jiandaoyun.UploadComm;
import com.cn.transfer.common.http.ApiClient;
import com.cn.transfer.common.utils.ConnmeUtils;
import com.cn.transfer.common.vo.UploadToken;
import com.cn.transfer.handle.impl.purchase.community.PurchaseCommunity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: weidian
 * @date: 2024/7/31 16:26
 * @Description: 图片上传修改
 */
@Slf4j
@RestController
public class Tupian {

    private static final String IMAGE_DIRECTORY = "/www/wwwroot/tupian/";

    @GetMapping("/tupiamn")
    public String callback() throws IOException {


        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "64ee9c37ee0a2c0007bc7afc");
        parameter.put("entry_id", "650ab93189d8223244d5b4cc");
        boolean fale = true;
        String zh = "";
        do {
            if (!zh.equals("")) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<UploadComm> mainFormDataList = JSONUtil.toList(objects, UploadComm.class);
            if (mainFormDataList.size() == 100) {
                zh = mainFormDataList.get(mainFormDataList.size() - 1).get_id();
            } else {
                fale = false;
            }
            for (UploadComm uploadComm : mainFormDataList) {
                boolean skipUploadComm = false; // 标记是否需要跳过当前UploadComm
                int ib = 0;
                Map<String, Object> parameters = new HashMap<>();
                parameters.put("app_id", "64ee9c37ee0a2c0007bc7afc");
                parameters.put("entry_id", "650ab93189d8223244d5b4cc");
                String s = IdUtil.randomUUID();
                parameters.put("transaction_id", s);
                String jsonSaleDelete = JSONUtil.toJsonStr(parameters);
                JSONObject jdySaledelete = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/file/get_upload_token", headers, jsonSaleDelete);
                String tokenList = jdySaledelete.getStr("token_and_url_list");
                JSONArray objectss = JSONUtil.parseArray(tokenList);
                List<UploadToken> uploadTokens = JSONUtil.toList(objectss, UploadToken.class);
                for (UploadToken uploadToken : uploadTokens) {
                    uploadToken.setTransactionId(s);
                }
                Map<String, Object> parameterInster = new HashMap<>();
                List<Map<String, Object>> mapList = new ArrayList<>();
                for (UploadComm.Mx mx : uploadComm.getMx()) {
                    if (mx.getAppendix().size()==0){
                        continue;
                    }
                    boolean allImagesSaved = true; // Track if all images are valid
                    for (UploadComm.Mx.Appendix appendix : mx.getAppendix()) {
                        try {
                            boolean isImage = saveImageToFolder(IMAGE_DIRECTORY, mx.getImgnames(), appendix.getUrl(), appendix.getName());
                            if (!isImage) {
                                allImagesSaved = false; // If any file is not an image, set to false
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                            allImagesSaved = false;
                        }
                    }
                    if (!allImagesSaved) {
                        skipUploadComm = true; // If any file is not an image, set flag to true
                        break; // Break out of the inner loop
                    }
                    // 获取指定目录下的所有图片文件

                    List<UploadToken> list = new ArrayList<>();
                    List<UploadToken> responseMap = new ArrayList<>();
                    File imageFolder = new File(IMAGE_DIRECTORY+mx.getImgnames());
                    File[] imageFiles = imageFolder.listFiles((dir, name) -> name.endsWith(".jpg") || name.endsWith(".png") ); // 可根据需要修改文件类型过滤条件
                    if (imageFiles != null) {
                        for (File imageFile : imageFiles) {
                            try {
                                // 从文件创建 MockMultipartFile 对象
                                FileItem fileItem = this.getMultipartFile(imageFile, imageFile.getName());
                                MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
                                // 将图片文件以form-data形式上传到后端
                                // 这里你可以调用你的业务逻辑来处理multipartFile，将其保存或进行其他操作
                                // 这里的示例只是将图片名称作为key，文件内容作为value放入响应Map中

                                UploadToken uploadToken = new UploadToken();
                                uploadToken.setImgName(imageFile.getName());
                                uploadToken.setImgFile(multipartFile.getBytes());
                                list.add(uploadToken);

                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }

                        for (UploadToken uploadToken : list) {
                            Header[] headersf = new Header[2];
                            headersf[0] = new BasicHeader("Authorization", "Bearer " + KeyConstant.JDY_KEY);
                            headersf[1] = new BasicHeader("Content-Type", "multipart/form-data");
                            HttpRequest post = HttpRequest.post(uploadTokens.get(ib).getUrl());
                            for (Header header : headersf) {
                                post.header(header.getName(), header.getValue());
                            }
                            String execute = post
                                    .form("token", uploadTokens.get(ib).getToken()) // 添加字符串参数
                                    .form("file", uploadToken.getImgFile(), uploadToken.getImgName()) // 添加文件参数
                                    .execute()
                                    .body();

                            JSONObject entries = JSONUtil.parseObj(execute);
                            UploadToken uploadToken1 = new UploadToken();
                            uploadToken1.setTransactionId(uploadTokens.get(ib).getTransactionId());
                            uploadToken1.setKey(entries.getStr("key"));
                            int lastDotIndex = uploadToken.getImgName().lastIndexOf(".");
                            String extension = uploadToken.getImgName().substring(0, lastDotIndex);

                            uploadToken1.setImgName(extension);
                            responseMap.add(uploadToken1);
                            ib++;
                        }

                        if (responseMap.isEmpty()) {
                            skipUploadComm = true; // 如果 responseMap 为空，则跳过当前 UploadComm
                            break; // 跳出当前 mx 循环
                        }

                        parameterInster.put("app_id", "64ee9c37ee0a2c0007bc7afc");
                        parameterInster.put("entry_id", "650ab93189d8223244d5b4cc");
                        parameterInster.put("data_id", uploadComm.get_id());
                        parameterInster.put("transaction_id", responseMap.get(0).getTransactionId());
                        List<String> keys = new ArrayList<>();
                        List<UploadToken> first10Elements;
                        if (responseMap.size() >= 10) {
                            first10Elements = responseMap.subList(0, 10);
                        } else {
                            first10Elements = responseMap; // 如果元素不足10个，将整个列表赋值给 first10Elements
                        }
                        for (UploadToken uploadToken : first10Elements) {
                            keys.add(uploadToken.getKey());
                        }
                        Map<String, Object> detailMap = new HashMap<>();

                        Map<String, Object> subProcessCode = new HashMap<>();
                        subProcessCode.put("value", mx.getSub_process_code());
                        detailMap.put("sub_process_code", subProcessCode);

                        Map<String, Object> style = new HashMap<>();
                        style.put("value", mx.getStyle());
                        detailMap.put("style", style);

                        Map<String, Object> productName = new HashMap<>();
                        productName.put("value", mx.getProduct_name());
                        detailMap.put("product_name", productName);

                        Map<String, Object> specificationsModel = new HashMap<>();
                        specificationsModel.put("value", mx.getSpecifications_model());
                        detailMap.put("specifications_model", specificationsModel);

                        Map<String, Object> productGrade = new HashMap<>();
                        productGrade.put("value", mx.getProduct_grade());
                        detailMap.put("product_grade", productGrade);

                        Map<String, Object> productKeyPoints = new HashMap<>();
                        productKeyPoints.put("value", mx.getProduct_key_points());
                        detailMap.put("product_key_points", productKeyPoints);

                        Map<String, Object> providedSamples = new HashMap<>();
                        providedSamples.put("value", mx.getProvided_samples());
                        detailMap.put("provided_samples", providedSamples);

                        Map<String, Object> unit = new HashMap<>();
                        unit.put("value", mx.getUnit());
                        detailMap.put("unit", unit);

                        Map<String, Object> shootingRequirementsRemarks = new HashMap<>();
                        shootingRequirementsRemarks.put("value", mx.getShooting_requirements_remarks());
                        detailMap.put("shooting_requirements_remarks", shootingRequirementsRemarks);

                        Map<String, Object> needToIncludeInCatalog = new HashMap<>();
                        needToIncludeInCatalog.put("value", mx.getNeed_to_include_in_catalog());
                        detailMap.put("need_to_include_in_catalog", needToIncludeInCatalog);

                        Map<String, Object> supplierMaterialAvailable = new HashMap<>();
                        supplierMaterialAvailable.put("value", mx.getSupplier_material_available());
                        detailMap.put("supplier_material_available", supplierMaterialAvailable);

                        Map<String, Object> supplierMaterialStoragePath = new HashMap<>();
                        supplierMaterialStoragePath.put("value", mx.getSupplier_material_storage_path());
                        detailMap.put("supplier_material_storage_path", supplierMaterialStoragePath);

                        Map<String, Object> disabled = new HashMap<>();
                        disabled.put("value", mx.getDisabled());
                        detailMap.put("disabled", disabled);

                        Map<String, Object> transfer = new HashMap<>();
                        transfer.put("value", mx.getTransfer());
                        detailMap.put("transfer", transfer);





                        Map<String, Object> appendixs = new HashMap<>();
                        Map<String, Object> appendix = new HashMap<>();

                        appendixs.put("value", keys);
                        appendix.put("value", keys);
                        detailMap.put("appendix_tu", appendixs);
                        detailMap.put("appendix", appendix);


                        Map<String, Object> imgnames = new HashMap<>();
                        imgnames.put("value", mx.getImgnames());
                        detailMap.put("imgnames", imgnames);
                        Map<String, Object> id = new HashMap<>();
                        id.put("value", mx.get_id());
                        detailMap.put("_id", id);


                        mapList.add(detailMap);

                    }
                }
                if (skipUploadComm) {
                    continue; // Skip this uploadComm and continue to the next one
                }
                if (parameterInster.isEmpty()) {
                    continue;
                }
                Map<String, Object> mxs = new HashMap<>();
                mxs.put("value", mapList);
                Map<String, Object> mxse = new HashMap<>();
                mxse.put("mx", mxs);
                parameterInster.put("data", mxse);
                String jsonSaled1 = JSONUtil.toJsonStr(parameterInster);
                log.info("当前正在修改附件发送给简道云的数据：==== " + jsonSaled1);
                JSONObject jdySale63 = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSaled1);
                log.info("修改的数据===" + jdySale63);
                deleteFolderContents(IMAGE_DIRECTORY);
                }

            }
            while (fale) ;


            return "success";
        }
        private FileItem getMultipartFile (File file, String fieldName){
            FileItemFactory factory = new DiskFileItemFactory(16, null);
            FileItem item = factory.createItem(fieldName, "text/plain", true, file.getName());
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            try {
                FileInputStream fis = new FileInputStream(file);
                OutputStream os = item.getOutputStream();
                while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
                os.close();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return item;
        }
    public static void deleteFolderContents(String folderPath) throws IOException {
        Path directory = Paths.get(folderPath);

        if (!Files.exists(directory) || !Files.isDirectory(directory)) {
            throw new IOException("Directory does not exist or is not a directory: " + folderPath);
        }

        // Walk through the directory and delete files and subdirectories
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory)) {
            for (Path entry : stream) {
                if (Files.isDirectory(entry)) {
                    deleteFolderContents(entry.toString());
                }
                Files.delete(entry);
                System.out.println("Deleted: " + entry.toString());
            }
        } catch (IOException e) {
            throw new IOException("Failed to read directory: " + folderPath, e);
        }
    }

    public static boolean saveImageToFolder(String rootFolderPath, String newFolderName, String imageUrl, String fileName) throws IOException {
        Path rootFolder = Paths.get(rootFolderPath);
        if (!Files.exists(rootFolder) || !Files.isDirectory(rootFolder)) {
            throw new IOException("Root directory does not exist or is not a directory: " + rootFolderPath);
        }

        // Create new folder
        Path newFolderPath = rootFolder.resolve(newFolderName);
        if (!Files.exists(newFolderPath)) {
            Files.createDirectories(newFolderPath);
        }

        // Download and save image to new folder
        Path imagePath = newFolderPath.resolve(fileName);

        try (InputStream in = new URL(imageUrl).openStream()) {
            Files.copy(in, imagePath, StandardCopyOption.REPLACE_EXISTING);

            // Check if file is an image
            String mimeType = Files.probeContentType(imagePath);
            if (mimeType == null || !mimeType.startsWith("image/")) {
                System.out.println("File is not an image: " + imagePath.toString());
                Files.delete(imagePath); // Delete non-image file
                return false;
            }

            System.out.println("Saved image: " + imagePath.toString());
            return true;
        } catch (IOException e) {
            throw new IOException("Failed to download image from " + imageUrl, e);
        }
    }

    }
